//上传背景图部分抽离
import { ref, computed } from "vue";
import { baseUrlApi } from "../../api/utils";
import { message } from "../../utils/message";
import { getToken } from "@/utils/auth";

import Add from "@iconify-icons/ep/plus";
import Eye from "@iconify-icons/ri/eye-line";
import Delete from "@iconify-icons/ri/delete-bin-7-line";

interface UploadConfig {
  field: string; // 字段名
  isSingle?: boolean; // 是否单图模式
  maxSize?: number; // 最大文件大小(MB)
  maxCount?: number; // 最大上传数量
}

export function uploadImageConfig(newFormInline, config: UploadConfig) {
  const curOpenImgIndex = ref(0);
  const dialogVisible = ref(false);
  const uploadUrl = baseUrlApi("common/upload/image");
  const uploadFileUrl = baseUrlApi("common/upload/file");

  // 获取预览图片列表
  const previewImageUrls = computed(() => {
    const value = newFormInline.value[config.field];
    if (config.isSingle) {
      return value ? [value] : [];
    }
    return Array.isArray(value) ? value.map(item => item.url || item) : [];
  });

  // 获取上传组件的文件列表
  const uploadFileList = computed(() => {
    const value = newFormInline.value[config.field];
    if (!value) return [];

    if (config.isSingle) {
      return [
        {
          name: "image",
          url: value
        }
      ];
    }
    return value;
  });

  /** 上传文件前校验 */
  const onBefore = file => {
    if (
      !["image/jpeg", "image/png", "image/gif", "image/webp"].includes(
        file.type
      )
    ) {
      message("只能上传图片");
      return false;
    }
    const isExceed = file.size / 1024 / 1024 > (config.maxSize || 5);
    if (isExceed) {
      message(`单个图片大小不能超过${config.maxSize || 5}MB`);
      return false;
    }
  };

  /** 上传成功回调 */
  const handleSuccess = (response, uploadFile) => {
    if (response.code === 200) {
      if (config.isSingle) {
        newFormInline.value[config.field] = response.data.path;
      } else {
        if (!Array.isArray(newFormInline.value[config.field])) {
          newFormInline.value[config.field] = [];
        }
        newFormInline.value[config.field].push({
          name: uploadFile.name,
          url: response.data.path
        });
      }
    }
  };

  /** 删除文件 */
  const handleRemove = () => {
    if (config.isSingle) {
      newFormInline.value[config.field] = "";
    } else {
      newFormInline.value[config.field] = [];
    }
  };

  /** 预览图片 */
  const handlePreview = () => {
    if (newFormInline.value[config.field]) {
      dialogVisible.value = true;
      curOpenImgIndex.value = 0;
    }
  };

  /** 超出限制提示 */
  const onExceed = () => {
    message(`最多只能上传${config.maxCount || 1}张图片`);
  };

  const headers = {
    Authorization: `Bearer ${getToken().accessToken}`
  };

  return {
    uploadUrl,
    headers,
    curOpenImgIndex,
    dialogVisible,
    previewImageUrls,
    uploadFileList,
    onBefore,
    handleSuccess,
    handleRemove,
    handlePreview,
    onExceed,
    Add,
    Eye,
    Delete,
    uploadFileUrl
  };
}
